/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.model.clazz;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;

import org.apache.commons.beanutils.PropertyUtils;

import com.koylu.caffein.Caffein;
import com.koylu.caffein.Cascade;
import com.koylu.caffein.exception.ClazzConfigException;
import com.koylu.caffein.model.caffein.CaffeinConfig;
import com.koylu.caffein.model.clazz.id.CompositeId;
import com.koylu.caffein.model.clazz.id.Id;
import com.koylu.caffein.model.clazz.validation.ValidateFor;
import com.koylu.caffein.model.clazz.validation.Validation;
import com.koylu.caffein.model.container.CollectionContainer;
import com.koylu.caffein.model.container.Container;
import com.koylu.caffein.model.container.ManyToManyContainer;
import com.koylu.caffein.model.handler.ClazzContainerHandler;
import com.koylu.caffein.model.handler.ManyToManyContainerHandler;
import com.koylu.caffein.query.GenericQuery;
import com.koylu.caffein.query.Query;
import com.koylu.caffein.query.filter.Filter;
import com.koylu.caffein.query.join.Join;
import com.koylu.caffein.query.order.Order;

public class ManyToMany extends Relation {
	
	private String name;
	private String clazz;
	private String table;
	private Node parent;
	private Clazz virtualClazz;
	private Collection<Key> children;
	private Collection<ForeignKey> foreignKeys;
	private Collection<Key> keys;
	private Index index;/* index column may be null */
	private Class returnType;
	private Class<?> proxyClass;
	private List<Validation> validations;
	private String cascade = Cascade.ALL.name();

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getClazz() {
		return clazz;
	}

	public void setClazz(String clazz) {
		this.clazz = clazz;
	}

	public Clazz getForeignClazz(CaffeinConfig caffeinConfig) throws Exception {
		Clazz clazzz = caffeinConfig.getClazz(clazz);
		if(clazzz == null){
			throw new ClazzConfigException("clazz not found:"+clazz, this);
		}
		return clazzz;
	}

	public Node getParent() {
		return parent;
	}

	public void setParent(Node parent) {
		this.parent = parent;
	}
	
	public String getTable() {
		return table;
	}

	public void setTable(String table) {
		this.table = table;
	}

	public void addChild(Node child) {
		if (children == null) {
			children = new ArrayList<Key>();
		}
		child.setParent(this);
		children.add((Key) child);
		if( child instanceof ForeignKey ){
			if(foreignKeys == null){
				foreignKeys = new ArrayList<ForeignKey>();
			}
			foreignKeys.add((ForeignKey)child);
		}else{
			if(keys == null){
				keys = new ArrayList<Key>();
			}
			keys.add((Key)child);
		}
	}

	public Collection<Key> getChildren() {
		return children;
	}

	public Collection<Key> getKeys() {
		return keys;
	}
	
	public Collection<ForeignKey> getForeignKeys() {
		return foreignKeys;
	}

	public Index getIndex() {
		return index;
	}

	public void setIndex(Index index) {
		this.index = index;
	}

	public String getCascade() {
		return cascade;
	}

	public void setCascade(String cascade) {
		this.cascade = cascade.toUpperCase(Locale.ENGLISH);
	}

	Boolean isSimple;
	public Object toObject(CaffeinConfig caffeinConfig, Object object, ResultSet resultSet) throws Exception {
		if (isSimple == null) {
			isSimple = !(((Clazz) getParent()).getId() instanceof CompositeId);
		}
		if (returnType == null) {
			returnType = collectionTypes.get(getRealClass(caffeinConfig).getName());
			if (index != null) {
				if (returnType.newInstance() instanceof Set) {
					returnType = null;
					throw new ClazzConfigException("use java.util.List for this element or remove index element", this);
				}
			}
		}
		if (isSimple) {
			return toSimpleObject(caffeinConfig, resultSet);
		}
		return toCompositeObject(caffeinConfig, resultSet);
	}

	private Key key = null;
	public Object toSimpleObject(CaffeinConfig caffeinConfig, ResultSet resultSet) throws Exception {
		if (key == null) {
			key = getKeys().iterator().next();
		}
		Query query = new GenericQuery(caffeinConfig, ((Clazz) getParent()), "local_table");
		query.addJoin(Join.inner("foreign_table", getName()), true);
		query.addFilter(Filter.eq("local_table", key.getRealNode(caffeinConfig).getPath(caffeinConfig), key.getConverter(caffeinConfig).columnToField(resultSet, key.getRealNode(caffeinConfig).getColumnAlias())));
		if (index != null) {
			query.addOrder(new OrderForIndex(getTable(), getIndex().getColumn(), "ASC"));
		}else{
			query.addOrder(new OrderForIndex(getTable(), key.getColumn(), "ASC"));
		}
		Object object = getProxyClass(caffeinConfig).newInstance();
		((ProxyObject) object).setHandler(new ManyToManyContainerHandler(caffeinConfig, getForeignClazz(caffeinConfig), returnType, query));
		return object;
	}

	public Object toCompositeObject(CaffeinConfig caffeinConfig, ResultSet resultSet) throws Exception {
		Query query = new GenericQuery(caffeinConfig, ((Clazz) getParent()), "local_table");
		query.addJoin(Join.inner("foreign_table", getName()), true);
		for (Key key : getKeys()) {
			query.addFilter(Filter.eq("local_table", key.getRealNode(caffeinConfig).getPath(caffeinConfig), key.getConverter(caffeinConfig).columnToField(resultSet, key.getRealNode(caffeinConfig).getColumnAlias())));
		}
		if (index != null) {
			query.addOrder(new OrderForIndex(getTable(), getIndex().getColumn(), "ASC"));
		}else{
			query.addOrder(new OrderForIndex(getTable(), keys.iterator().next().getColumn(), "ASC"));
		}
		Object object = getProxyClass(caffeinConfig).newInstance();
		((ProxyObject) object).setHandler(new ManyToManyContainerHandler(caffeinConfig, getForeignClazz(caffeinConfig), returnType, query));
		return object;
	}
	
	public Object toEmptyObject(CaffeinConfig caffeinConfig, Clazz clazz) throws Exception {
		if (returnType == null) {
			returnType = collectionTypes.get(getRealClass(caffeinConfig).getName());
			if (index != null) {
				if (returnType.newInstance() instanceof Set) {
					returnType = null;
					throw new ClazzConfigException("use java.util.List for this element or remove index element", this);
				}
			}
		}
		return returnType.newInstance();
	}
	
	public Class<?> getProxyClass(CaffeinConfig caffeinConfig) throws Exception {
		if(proxyClass == null){
			ProxyFactory proxyFactory = new ProxyFactory();
			proxyFactory.setSuperclass(returnType);
			proxyFactory.setInterfaces(ManyToManyContainer.interfaces);
			proxyFactory.setFilter(Container.methodFilter);
			proxyClass = proxyFactory.createClass();
		}
		return proxyClass;
	}
	
	private Class<?> realClass;
	private Class<?> getRealClass(CaffeinConfig caffeinConfig) throws Exception {
		if(realClass == null){
			if(virtualClass == null){
				realClass = CaffeinConfig.getFieldType(((Clazz)getParent()).getRealClass(caffeinConfig), name);
			}else{
				realClass = virtualClass;
			}			
		}
		return realClass;
	}

	private Class<?> virtualClass;
	public Class<?> toVirtualClass(CaffeinConfig caffeinConfig) throws Exception {
		if(virtualClass == null){
			virtualClass = List.class;
		}
		return virtualClass;
	}

	public Object copy(CaffeinConfig caffeinConfig, Object object) throws Exception {
		CollectionContainer collectionContainer = (CollectionContainer) object;
		Object newObject = getProxyClass(caffeinConfig).newInstance();
		((ProxyObject) newObject).setHandler(new ManyToManyContainerHandler(caffeinConfig, getForeignClazz(caffeinConfig), returnType, collectionContainer.getQuery()));
		return newObject;
	}

	public Clazz getVirtualClazz(CaffeinConfig caffeinConfig) throws Exception {
		if (virtualClazz == null) {
			virtualClazz = new Clazz();
			virtualClazz.setName(((Clazz)getParent()).getName()+"."+getName());
			virtualClazz.setSchema(((Clazz)getParent()).getSchema());
			virtualClazz.setTable(table);
			virtualClazz.setCacheable(false);
			CompositeId compositeId = new CompositeId();
			compositeId.setName("id");
			virtualClazz.addChild(compositeId);
			ManyToOne local = new ManyToOne();
			local.setName("local");
			local.setClazz(((Clazz) getParent()).getName());
			ManyToOne foreign = new ManyToOne();
			foreign.setName("foreign");
			foreign.setClazz(getClazz());
			for (Key key : getChildren()) {
				ForeignKey fk = new ForeignKey();
				fk.setColumn(key.getColumn());
				fk.setRefColumn(key.getRefColumn(caffeinConfig));
				fk.setConverter(key.getConverter());
				if (key instanceof ForeignKey) {
					foreign.addChild(fk);
				} else {
					local.addChild(fk);
				}
			}
			compositeId.addChild(local);
			compositeId.addChild(foreign);
			if (index != null) {
				Property property = new Property();
				property.setName("index");
				property.setColumn(index.getColumn());
				virtualClazz.addChild(property);
			}
			virtualClazz.prepareColumnMap();
		}
		return virtualClazz;
	}
	
	public List<Validation> getValidations() {
		return validations;
	}

	public void setValidations(List<Validation> validations) {
		this.validations = validations;
	}
	
	public void validate(CaffeinConfig caffeinConfig, Clazz clazz, Object object, ValidateFor validateFor) throws Exception {
		if (validations != null) {
			for (Validation validation : validations) {
				validation.validate(caffeinConfig, clazz, this, object, validateFor);
			}
		}
	}
	
	public void save(CaffeinConfig caffeinConfig, Connection connection, Object object) throws Exception {
		if (Cascade.ALL.equals(Cascade.valueOf(cascade))) {
			Collection<?> manyToManyCollection = (Collection<?>) PropertyUtils.getProperty(object, getName());
			if (manyToManyCollection != null) {
				Caffein caffein = caffeinConfig.getCaffein();
				Clazz manyToManyVirtualClazz = getVirtualClazz(caffeinConfig);
				Id id = manyToManyVirtualClazz.getId();
				int k = 0;
				Object manyToManyObject = manyToManyVirtualClazz.getProxyClass(caffeinConfig).newInstance();
				Object manyToManyObjectId = id.toEmptyObject(caffeinConfig, manyToManyVirtualClazz);
				PropertyUtils.setProperty(manyToManyObject, id.getName(), manyToManyObjectId);
				PropertyUtils.setProperty(manyToManyObjectId, "local", object);
				for (Object foreignObject : manyToManyCollection) {
					PropertyUtils.setProperty(manyToManyObjectId, "foreign", foreignObject);
					if( getIndex() != null ){
						PropertyUtils.setProperty(manyToManyObject, "index", k++);
					}
					try {
						caffein.save(manyToManyVirtualClazz, connection, manyToManyObject);	
					} catch (Exception e) {
						throw new RuntimeException("manyToMany save error["+name+"]", e);
					}
				}
			}
		}
	}
	
	public void update(CaffeinConfig caffeinConfig, Connection connection, Object object) throws Exception {
		if (Cascade.ALL.equals(Cascade.valueOf(cascade))) {
			ManyToManyContainer manyToManyContainer = (ManyToManyContainer) PropertyUtils.getProperty(object, getName());
			if (manyToManyContainer.getContainerCollection() != null) {
				Caffein caffein = caffeinConfig.getCaffein();
				manyToManyContainer.trackIdChanges();
				Clazz manyToManyVirtualClazz = getVirtualClazz(caffeinConfig);
				Object manyToManyObjectId = manyToManyVirtualClazz.getId().toEmptyObject(caffeinConfig, manyToManyVirtualClazz);
				PropertyUtils.setProperty(manyToManyObjectId, "local", object);
				for (Object removedObject : manyToManyContainer.getRemovedObjects()) {
					PropertyUtils.setProperty(manyToManyObjectId, "foreign", removedObject);
					try {
						caffein.delete(manyToManyVirtualClazz, connection, manyToManyObjectId);	
					} catch (Exception e) {
						throw new RuntimeException("manyToMany delete error["+name+"]", e);
					}
				}
				Object manyToManyObject = manyToManyVirtualClazz.getProxyClass(caffeinConfig).newInstance();
				PropertyUtils.setProperty(manyToManyObject, manyToManyVirtualClazz.getId().getName(), manyToManyObjectId);
				if(index != null){
					PropertyUtils.setProperty(manyToManyObject, "index", 0);					
				}
				for (Object addedObject : manyToManyContainer.getAddedObjects()) {
					PropertyUtils.setProperty(manyToManyObjectId, "foreign", addedObject);
					try {
						caffein.save(manyToManyVirtualClazz, connection, manyToManyObject);						
					} catch (Exception e) {
						throw new RuntimeException("manyToMany save error["+name+"]", e);
					}
				}
				if(index != null){
					if (manyToManyContainer.isIndexChanged()) {
						int k = 0;
						for (Object foreignObject : manyToManyContainer.getContainerCollection()) {
							PropertyUtils.setProperty(manyToManyObjectId, "foreign", foreignObject);
							PropertyUtils.setProperty(manyToManyObject, "index", k++);
							((ProxyObject) manyToManyObject).setHandler(new ClazzContainerHandler(caffeinConfig, manyToManyVirtualClazz, manyToManyObjectId, true));
							try {
								caffein.update(manyToManyVirtualClazz, connection, manyToManyObject);								
							} catch (Exception e) {
								throw new RuntimeException("manyToMany update error["+name+"]", e);
							}
						}
					}
				}
			}
			manyToManyContainer.resetContainer();
		}		
	}
	
	public void delete(CaffeinConfig caffeinConfig, Clazz clazz, Connection connection, Object object) throws Exception {
		if (Cascade.ALL.equals(Cascade.valueOf(cascade))) {
			if( ((Collection<?>)PropertyUtils.getProperty(object, name)).size() > 0 ){
				Clazz virtualClazz = getVirtualClazz(caffeinConfig);
				PreparedStatement preparedStatement = caffeinConfig.getObjectToQuery().deleteManyToMany(caffeinConfig, this, connection, virtualClazz, object);
				try {
					preparedStatement.executeUpdate();	
				} catch (Exception e) {
					throw new RuntimeException("manyToMany delete error["+name+"]", e);
				}finally{
					if(preparedStatement != null){
						try {
							preparedStatement.close();							
						} catch (Exception e) {}
					}
				}
			}
		}
	}
	
	private static class OrderForIndex extends Order {
		
		private String alias;
		private String column;
		private String type;
		private StringBuffer query = null;
		
		public OrderForIndex(String alias, String column, String type) {
			super(alias, column, type);
			this.alias = alias;
			this.column = column;
			this.type = type;
		}
		
		public StringBuffer toQuery(CaffeinConfig caffeinConfig, Map<String, Clazz> aliasMap) throws Exception {
			if(query == null){
				query = new StringBuffer(alias).append(".").append(column).append(" ").append(type); 
			}
			return query;
		}
	}
	
	public String getPath(CaffeinConfig caffeinConfig) throws Exception {
		return name;
	}
	
	public String toString() {
		return getClass().getName()+"["+name+"]";
	}
}